/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 * BaseSystemRelationService
 * 系统关联表
 * 修改纪录
 * 2021-01-27 版本：1.0 zhanglongfei 创建。
 * 
 * @version 版本：1.0
 * @author 作者：zhanglongfei
 * 创建日期：2021-01-27
 */
package com.topscomm.base.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.base.pojo.BaseSystemRelationEntity;
import com.topscomm.base.service.IBaseSystemRelationService;
import com.topscomm.base.service.impl.auto.BaseSystemRelationServiceAuto;
import com.topscomm.dsp.api.DspServiceApi;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.vo.Page;

@Service(value = "baseSystemRelationService")
@Scope(value = "singleton")
public class BaseSystemRelationService extends BaseSystemRelationServiceAuto implements IBaseSystemRelationService {
	@Autowired
	private DspServiceApi dspServiceApi;

	/**
	 * @description:同步其他系统的状态
	 * @author: zhanglongfei
	 * @date: 2021年1月30日上午9:57:17
	 * @modify:
	 */
	public void syncRelationOrderState() {
		List<BaseSystemRelationEntity> list = queryByWhere("state!=9 and enabled=1");
		for (BaseSystemRelationEntity entity : list) {
			if (!"Toa".equals(entity.getRelationsystem()))
				continue;
			try {
				Map<String, Object> map = new HashMap<>();
				map.put("sourcetype", entity.getRelationsourcetype());
				map.put("id", entity.getRelationsourceid());
				Page page = dspServiceApi.query("MCRQueryOABusiness", map);
				// 没有数据，则删除
				if (page.getTotalCount() == 0) {
					entity.setEnabled(0);
					updateEntity(entity);
					continue;
				}
				Map<?, ?> relationMap = (Map<?, ?>) page.getDataList().get(0);
				String newState = ConvertUtil.convertToString(relationMap.get("STATE"));
				Date modifyTime = ConvertUtil.convertToDate(relationMap.get("MODIFIEDON"));
				// 如果长期停留在开立和退回状态不变，那么就不再更新
				if (("0".equals(entity.getState()) || "2".equals(entity.getState())) && newState.equals(entity.getState())) {
					long diff = new Date().getTime() - modifyTime.getTime();
					// 超过20天没更新过，那么就不再查询此单据
					if (diff > 1728000000) {
						entity.setEnabled(0);
						updateEntity(entity);
						continue;
					}
				}
				entity.setLastupdatetime(new Date());
				entity.setLatestphase(ConvertUtil.convertToString(relationMap.get("LASTESTPHASE")));
				entity.setState(newState);
				entity.setUsercode(ConvertUtil.convertToString(relationMap.get("USERCODE")));
				entity.setUsername(ConvertUtil.convertToString(relationMap.get("USERNAME")));
				updateEntity(entity);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(e.getMessage());
			}
		}
	}
}
